﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public partial class MedicFSM : FriendFSM
{
    protected bool m_bFollowHealOrder = true;
    protected bool m_bFoundPatient = false;

    List<GameObject> m_pLineList;
    GameObject m_pPatientObj;


    void OnEnable()
    {
        m_bFollowHealOrder = true;
        m_pLineList = new List<GameObject>();

        gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.IDLE;

        StartCoroutine(InitState());
    }

    IEnumerator InitState()
    {
        gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.IDLE;
        gameObject.transform.GetChild(0).GetChild(0).GetComponent<UnitHeadState>().SetHeadAnim();

        yield return null;

        SetState(gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState);
    }


    void SetState(BASEUNIT_STATE iStateKey)
    {

        switch (iStateKey)
        {
            case BASEUNIT_STATE.IDLE:
                StartCoroutine(IdleState());
                break;
            case BASEUNIT_STATE.MOVE:
                StartCoroutine(MoveState());
                break;
            case BASEUNIT_STATE.COVER:
                StartCoroutine(CoverState());
                break;
            case BASEUNIT_STATE.CLOSEATTACK:
                StartCoroutine(CloseAtkState());
                break;
            case BASEUNIT_STATE.AIM:
                StartCoroutine(AImState());
                break;
            case BASEUNIT_STATE.RELOAD:
                StartCoroutine(ReloadState());
                break;
            case BASEUNIT_STATE.DAMAGE:
                StartCoroutine(DamageState());
                break;
            case BASEUNIT_STATE.DEAD:
                StartCoroutine(DeadState());
                break;
            case BASEUNIT_STATE.HEAL:
                StartCoroutine(HealState());
                break;
            case BASEUNIT_STATE.SUPPLY:
                StartCoroutine(SupplyState());
                break;
            default:
                Debug.Log("StateKey Error!");
                StartCoroutine(IdleState());
                break;
        }

    }


    protected bool InjuryTarget_Find(string strFactionTag) //시야내에 가장 가까운 환자를 찾아냄
    {
        Collider2D[] CollObjs = (Physics2D.OverlapCircleAll(gameObject.transform.position,
            gameObject.GetComponent<UnitStatus>().m_unitData.fSightRange));

        float distance = Mathf.Infinity;


        foreach (Collider2D Obj in CollObjs)
        {
            if (Obj.gameObject.tag == strFactionTag)
            {
                if (Obj.gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState != BASEUNIT_STATE.DEAD
                    && Obj.gameObject.GetComponent<UnitStatus>().m_unitData.iCurrentHP < Obj.gameObject.GetComponent<UnitStatus>().m_unitData.iMaxHP
                    && Obj.gameObject != gameObject )
                {
                    Vector3 diff = Obj.gameObject.transform.position - gameObject.transform.position;
                    float curDistance = diff.sqrMagnitude;
                    if (curDistance < distance)
                    {
                        m_pPatientObj = Obj.gameObject;
                        distance = curDistance;
                    }

                    m_bFoundPatient = true;
                }

            }
        }

        if (m_pPatientObj == null)
            return false;
        else
            return true;
    }

    protected virtual void HealEnable()
    {
        if (!m_bFoundPatient)
        {
            if (InjuryTarget_Find("Player"))
            {
                m_vecDest = m_pPatientObj.transform.position - new Vector3(0, 0.35f);

                if (!Calculate.AStarStart(gameObject, m_vecDest, ref m_BestList, m_iPrevTIleIdx, m_iPrevTileOption))
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.MOVE;
                else
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.HEAL;
            }
        }
    }

    protected override void MoveOrder()
    {
        if (MouseColCheck() && GameObject.Find("RightWdw").GetComponent<RightWdwMgr>().CurWinNum == 0)
        {
            if (m_pHoverUI == null)
                m_pHoverUI = ResourceMgr.GetInstance().CreateHoverUnitInformUI(gameObject);

            if (m_pSelectUI == null)
            {
                m_pSelectUI = ResourceMgr.GetInstance().CreateSelectUI(gameObject);
                m_pSelectUI.GetComponent<SelectUI>().m_pOwner = gameObject;
                m_pSelectUI.GetComponent<SelectUI>().SetAlpha(0.3f);
            }

            //Line///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            m_pLineList = ResourceMgr.GetInstance().DrawBoundaryUnitLine(gameObject, m_pLineList, gameObject.GetComponent<UnitStatus>().m_unitData.fSightRange, new Color(212 / 255f, 117 / 255f, 117 / 255f));
            //Line///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //상태이상 출력
            for (int i = 0; i < gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange.Count; ++i)
            {
                if (gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i] != null)
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i].active = true;
            }

            if (Input.GetMouseButtonDown(0) && (!m_bSelectChk))
            {
                if (InputMgr.GetInstance().m_bUnitSelected == true)
                {
                    Debug.Log(InputMgr.GetInstance().m_bUnitSelected);
                    return;
                }

                if (InputMgr.GetInstance().m_MouseInputState == MOUSEINPUT_STATE.NORMAL)
                {
                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SelectedUnit = gameObject;
                    m_bSelectChk = true;

                    InputMgr.GetInstance().m_bUnitSelected = true;

                    if (m_pSelectUI != null)
                        m_pSelectUI.GetComponent<SelectUI>().SetAlpha(1.0f);
                }
                else if (InputMgr.GetInstance().m_MouseInputState == MOUSEINPUT_STATE.SUPPLY) // 무기보급
                {
                    InputMgr.GetInstance().m_MouseInputState = MOUSEINPUT_STATE.NORMAL;
                    gameObject.GetComponent<UnitStatus>().m_WeaponData = GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SupplyWeaponQueue;
                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().ArmoryWeaponList.Remove(GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SupplyWeaponQueue);

                    string strType = "null";

                    if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_WeaponType == WEAPON_TYPE.PISTOL)
                    {
                        strType = "Pistol";
                        gameObject.transform.GetChild(1).GetComponent<AudioSource>().clip = Resources.Load<AudioClip>("Audio/Pistol");
                        gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Pistol");
                    }
                    else if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_WeaponType == WEAPON_TYPE.RIFLE)
                    {
                        if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_strWeaponName == "FN303")
                        {
                            gameObject.transform.GetChild(1).GetComponent<AudioSource>().clip = Resources.Load<AudioClip>("Audio/Weapon/FN303/4");
                            gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Riotgun");
                        }
                        else
                        {
                            gameObject.transform.GetChild(1).GetComponent<AudioSource>().clip = Resources.Load<AudioClip>("Audio/Rifle");
                            gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Rifle");
                        }
                        strType = "Rifle";
                    }

                    string s = string.Format("{0}{1}{2}{3}", "Anim/Unit/", gameObject.transform.parent.parent.name, "/", strType);
                    gameObject.GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>(s);


                    GameObject.Find("MainCamera").GetComponent<AudioSource>().PlayOneShot(Resources.Load<AudioClip>("Audio/Reload0"));
                }
            }
        }
        else if (!MouseColCheck())
        {
            if (!m_bSelectChk)
            {
                if (m_pSelectUI != null)
                    Destroy(m_pSelectUI);
            }
            if (!InputMgr.GetInstance().m_bUnitHoverUI)
            {
                if (m_pHoverUI != null)
                    Destroy(m_pHoverUI);
            }

            //상태이상 출력 삭제
            for (int i = 0; i < gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange.Count; ++i)
            {
                if (gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i] != null)
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i].active = false;
            }

            //Line///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (m_pLineList.Count != 0)
            {
                for (int i = 0; i < m_pLineList.Count; ++i)
                {
                    if (m_pLineList[i])
                        Destroy(m_pLineList[i]);
                }
                m_pLineList.Clear();
            }
            //Line///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }

        //Mouse MovePos Select
        if (Input.GetMouseButtonDown(1) && m_bSelectChk)
        {
            if (m_bFoundPatient)
            {
                m_bFoundPatient = false;

            }

            m_bSelectChk = false;
            GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SelectedUnit = null;

            m_vecDest = Calculate.GetMousePos();


            InputMgr.GetInstance().m_bUnitSelected = false;

            //End
            if (!Calculate.AStarStart(gameObject, m_vecDest, ref m_BestList, m_iPrevTIleIdx, m_iPrevTileOption))
                gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.MOVE;

            Destroy(m_pSelectUI);
        }
    }

    protected override BASEUNIT_STATE AStarMove()
    {
        if (m_BestList == null)
        {
            if (m_bFoundPatient)
                return BASEUNIT_STATE.HEAL;
           
            if (m_bSupply)
                return BASEUNIT_STATE.SUPPLY;
            else
                return BASEUNIT_STATE.IDLE;
        }

        GameObject NextTile = GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[m_BestList[0]];

        if (NextTile.GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BLOCK || NextTile.GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BUILD)
        {
            Calculate.AStarStart(gameObject, m_vecDest, ref m_BestList, m_iPrevTIleIdx, m_iPrevTileOption);

        }

        Vector2 vecNextDest = NextTile.transform.position;

        Calculate.RotToDest(gameObject, vecNextDest);
        Calculate.MoveToDest(gameObject, vecNextDest, gameObject.GetComponent<UnitStatus>().m_unitData.fSpeed);

        if (Vector2.Distance(gameObject.transform.position, vecNextDest) < 0.001f)
        {

            gameObject.transform.position = vecNextDest;
            m_iCurrentTileIdx = m_BestList[0];

            m_BestList.Remove(m_BestList[0]);

            if (m_BestList.Count == 0)
            {
                m_BestList.Clear();
                m_BestList = null;

                if (m_bFoundPatient)
                    return BASEUNIT_STATE.HEAL;

                if (m_bSupply)
                    return BASEUNIT_STATE.SUPPLY;
                else
                    return BASEUNIT_STATE.IDLE;
            }
        }

        return BASEUNIT_STATE.MOVE;
    }
}
